package ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Timer;
import java.util.TimerTask;

import javax.management.timer.TimerMBean;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.WindowConstants;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;

public class MainFrame extends JFrame {

	private JButton startBt;
	private JButton ruleBt;
	private JButton aboutBt;
	private JButton stopBt;
	private JButton updateSpeedBt;
	private JSlider speedSlider;
	private JLabel amountLabel;

	private int speed = 10;
	private boolean stop;

	private Timer timer = new Timer();

	/*
	 * 数组的第1行第1个（1,1） 为画布的第1行第1个（0,0）
	 */
	private int[][] matrix = new int[150][76];
	private int[][] nextMatrix = new int[150][76];

	public MainFrame() {
		this.setTitle("LifeGame(生命游戏)");
		this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

		Toolkit tool = Toolkit.getDefaultToolkit();// 创建系统该默认组件工具包
		Dimension d = tool.getScreenSize();// 获取屏幕尺寸，赋给一个二维坐标对象
		this.setSize(d.width - d.width / 5 - 1, d.height - d.height / 5 + 1);// 设置窗体大小
		this.setResizable(false);
		// 让主窗体在屏幕中间显示
		this.setLocation((d.width - getWidth()) / 2, (d.height - getHeight()) / 2);

		uiInit();

		Timer timer = new Timer();
		TimerTask task = new TimerTask() {
			@Override
			public void run() {

				if (!stop) {
					if (startBt.getText().equals("开始游戏")) {
						try {
							Thread.sleep(100);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					} else {
						try {
							Thread.sleep(50 * speed);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}

					}
					repaint();
				}
			}
		};
		timer.schedule(task, 0, 100);

		addActionListener();
	}

	private void uiInit() {
		JToolBar toolBar = new JToolBar("工具栏");
		toolBar.addSeparator(new Dimension(15, 0));
		startBt = new JButton("开始游戏");
		toolBar.add(startBt);
		toolBar.addSeparator(new Dimension(15, 0));
		stopBt = new JButton("暂停游戏");
		stopBt.setEnabled(false);
		toolBar.add(stopBt);
		toolBar.addSeparator(new Dimension(15, 0));
		ruleBt = new JButton("游戏规则");
		toolBar.add(ruleBt);
		toolBar.addSeparator(new Dimension(15, 0));
		aboutBt = new JButton("开发人员");
		toolBar.add(aboutBt);
		toolBar.addSeparator(new Dimension(15, 0));
		toolBar.add(new JLabel("游戏速度(ms)"));
		toolBar.addSeparator(new Dimension(10, 0));
		speedSlider = new JSlider();
		speedSlider.setValue(10);
		toolBar.add(speedSlider);
		speedSlider.setEnabled(false);
		toolBar.addSeparator(new Dimension(10, 0));
		updateSpeedBt = new JButton("修改");
		toolBar.add(updateSpeedBt);
		toolBar.addSeparator(new Dimension(15, 0));
		amountLabel = new JLabel("生命总数：00000");
		toolBar.add(amountLabel);
		toolBar.addSeparator(new Dimension(15, 0));
		toolBar.setFloatable(false);

		JPanel paintPanel = new JPanel() {

			@Override
			public void paint(Graphics g) {
				super.paint(g);
				for (int x = 0; x <= 1480; x += 10) {
					g.drawLine(x, 0, x, this.getHeight());
				}
				for (int y = 0; y <= 740; y += 10) {
					g.drawLine(0, y, this.getWidth(), y);
				}

				// 为开始游戏时
				if (startBt.getText().equals("开始游戏")) {
					for (int y = 1; y <= 74; y++) {
						for (int x = 1; x <= 148; x++) {
							if (matrix[x][y] == 1) {
								g.setColor(Color.BLACK);
							} else if (matrix[x][y] == 0) {
								g.setColor(Color.WHITE);
							}
							// 数组（1,1）对应画布（0,0）
							g.fillRect((x - 1) * 10 + 1, (y - 1) * 10 + 1, 10 - 1, 10 - 1);
						}
					}
				} else {
					arrayToArray(nextMatrix, matrix);
					for (int y = 1; y <= 74; y++) {
						for (int x = 1; x <= 148; x++) {
							int lives = findLifedNum(x, y);
							if (matrix[x][y] == 0 && lives == 3) {
								nextMatrix[x][y] = 1;
							} else if (matrix[x][y] == 1 && (lives < 2 || lives > 3)) {
								nextMatrix[x][y] = 0;
							}
						}
					}
					arrayToArray(matrix, nextMatrix);
					int lives = 0;
					for (int y = 1; y <= 74; y++) {
						for (int x = 1; x <= 148; x++) {
							if (nextMatrix[x][y] == 1) {
								g.setColor(Color.BLACK);
								lives += 1;
							} else if (nextMatrix[x][y] == 0) {
								g.setColor(Color.WHITE);
							}
							// 数组（1,1）对应画布（0,0）
							// 数组（148,74）对应画布（147,73）
							g.fillRect((x - 1) * 10 + 1, (y - 1) * 10 + 1, 10 - 1, 10 - 1);
						}
					}
					String s = String.valueOf(lives);
					if (s.length() == 1) {
						amountLabel.setText("生命总数：0000" + s);
					} else if (s.length() == 2) {
						amountLabel.setText("生命总数：000" + s);
					} else if (s.length() == 3) {
						amountLabel.setText("生命总数：00" + s);
					} else if (s.length() == 4) {
						amountLabel.setText("生命总数：0" + s);
					} else if (s.length() == 5) {
						amountLabel.setText("生命总数：" + s);
					}
				}
			}

			public int findLifedNum(int x, int y) {
				return matrix[x - 1][y - 1] + matrix[x - 1][y] + matrix[x - 1][y + 1] + matrix[x][y - 1]
						+ matrix[x][y + 1] + matrix[x + 1][y - 1] + matrix[x + 1][y] + matrix[x + 1][y + 1];
			}

		};

		this.add(toolBar, BorderLayout.NORTH);
		this.add(paintPanel, BorderLayout.CENTER);
	}

	private void arrayToArray(int[][] a, int[][] b) {
		for (int y = 0; y <= 75; y++) {
			for (int x = 0; x <= 149; x++) {
				a[x][y] = b[x][y];
			}
		}
	}

	private void addActionListener() {
		startBt.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if (startBt.getText().equals("开始游戏")) {
					startBt.setText("结束游戏");
					stopBt.setEnabled(true);
				} else {
					stop = false;
					amountLabel.setText("生命总数：00000");
					stopBt.setText("暂停游戏");
					startBt.setText("开始游戏");
					stopBt.setEnabled(false);
					for (int y = 0; y < 76; y++) {
						for (int x = 0; x < 150; x++) {
							matrix[x][y] = 0;
						}
					}
				}
			}
		});

		stopBt.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if (stopBt.getText().equals("暂停游戏")) {
					stopBt.setText("继续游戏");
				} else {
					stopBt.setText("暂停游戏");
				}
				stop = !stop;
			}
		});

		aboutBt.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				new AboutUsFrame().setVisible(true);
			}
		});

		ruleBt.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				new RuleFrame().setVisible(true);
			}
		});

		this.addMouseListener(new MouseAdapter() {// 界面点击事件
			int x, y;

			@Override
			public void mousePressed(MouseEvent e) {
				if (startBt.getText().equals("开始游戏")) {
					x = (e.getX() - 27) / 10;
					y = (e.getY() - 87) / 10;
					// 获取界面第x行第有y个 对应的数组（x+1,y+1）
					if ((x >= 0 && x < 148) && (y >= 0 && y < 74)) {
						if (matrix[x + 1][y + 1] != 1) {
							matrix[x + 1][y + 1] = 1;
						} else {
							matrix[x + 1][y + 1] = 0;
						}
					}
				}
			}
		});

		updateSpeedBt.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if (updateSpeedBt.getText().equals("修改")) {
					updateSpeedBt.setText("确定");
					speedSlider.setEnabled(true);
				} else {
					updateSpeedBt.setText("修改");
					speedSlider.setEnabled(false);
					speed = speedSlider.getValue();
				}
			}
		});

	}
}
